﻿using IniReadWrite;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VisionRoc.Core
{

    /// <summary>
    /// 松下协议通信
    /// </summary>
    public class PanasonicMewtocol
    {
        public bool State = false;
        public string PanasonicPath;
        public PanasonicMewtocol(string _Path)
        {
            try
            {
                //判断文件路径是否存在
                if (!Directory.Exists(_Path))
                {
                    Directory.CreateDirectory(_Path);
                }
                PanasonicPath = _Path + "\\PanasonicMewtocol.ini";
                //OpenResult = false;
                //判断文件是否存在
                if (File.Exists(PanasonicPath))
                {
                    ReadParameter();
                    State = OpenSerial(COM, BaudRate, DataBits, StopBits, BarityBit);
                }
                else
                {
                    State = false;
                }
            }
            catch
            {
                State = false;
            }
            if (State)
            {
                Global.AddLogInfoEvent(LogLevel.OK, $"PanasonicMewtocol 通信打开成功 串口号：{COM},波特率：{BaudRate},数据位：{DataBits},停止位：{StopBits},校验位：{BarityBit}");
            }
            else
            {
                Global.AddLogInfoEvent(LogLevel.Error, $"PanasonicMewtocol 通信打开失败！ 串口号：{COM},波特率：{BaudRate},数据位：{DataBits},停止位：{StopBits},校验位：{BarityBit}");
            }

        }


        /// <summary>
        /// 串口号
        /// </summary>
        public string COM { get; set; }

        /// <summary>
        /// 波特率
        /// </summary>
        public int BaudRate { get; set; }

        /// <summary>
        /// 奇偶校验位
        /// </summary>
        public int BarityBit { get; set; }

        /// <summary>
        /// 数据位
        /// </summary>
        public int DataBits { get; set; }

        /// <summary>
        /// 停止位
        /// </summary>
        public int StopBits { get; set; }

        string[] protname;

        public HslCommunication.Profinet.Panasonic.PanasonicMewtocol PLC = null;

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="PortName">串口号</param>
        /// <param name="baudRate">波特率</param>
        /// <param name="dataBits">数据位</param>
        /// <param name="stopBits">停止位</param>
        /// <param name="Parity">校验位</param>
        /// <returns></returns>
        public bool OpenSerial(string PortName, int baudRate, int dataBits, int stopBits, int Parity)
        {
            try
            {
                PLC = new HslCommunication.Profinet.Panasonic.PanasonicMewtocol();
                PLC.SerialPortInni(sp =>
                {
                    sp.PortName = PortName;
                    sp.BaudRate = baudRate;
                    sp.DataBits = dataBits;
                    sp.StopBits = stopBits == 0 ? System.IO.Ports.StopBits.None : (stopBits == 1 ? System.IO.Ports.StopBits.One : System.IO.Ports.StopBits.Two);  //停止位数
                    sp.Parity = Parity == 0 ? System.IO.Ports.Parity.None : (Parity == 1 ? System.IO.Ports.Parity.Odd : System.IO.Ports.Parity.Even);
                    sp.RtsEnable = false;
                });
                PLC.ReceiveTimeout = 5000;   // 接收超时，单位毫秒
                PLC.Station = 238;
                PLC.Open();
                if (PLC.IsOpen())
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 加载串口至控件
        /// </summary>
        /// <param name="COM">串口号</param>
        /// <param name="Paud">波特率</param>
        /// <param name="Parity">校验位</param>
        /// <param name="StopBits">停止位</param>
        /// <param name="DataBits">数据位</param>
        public void LoadSerialPort(ComboBox COM, ComboBox Paud, ComboBox Parity, ComboBox StopBits, ComboBox DataBits)
        {
            #region 初始化串口
            //端口号 
            string[] PortList = SerialPort.GetPortNames();
            if (PortList.Length > 0)
            {
                COM.Items.AddRange(PortList);
                COM.SelectedIndex = 0;
            }
            else
            {
                COM.Text = "NULL";
            }

            //波特率
            Paud.DataSource = new string[] { "2400", "4800", "9600", "19200", "38400", "115200" };
            //校验位
            Parity.DataSource = new string[] { "0", "1", "2" };
            //停止位
            StopBits.DataSource = new string[] { "1", "2" };
            StopBits.SelectedIndex = 1;
            //数据位
            DataBits.DataSource = new string[] { "8", "7", "6", "5" };
            #endregion
        }


        /// <summary>
        /// 保存串口参数
        /// </summary>
        public void WriteParameter()
        {
            IniAPI.INIWriteValue(PanasonicPath, "SerialPortParameter", "COM", COM.ToString());
            IniAPI.INIWriteValue(PanasonicPath, "SerialPortParameter", "Baud", BaudRate.ToString());
            IniAPI.INIWriteValue(PanasonicPath, "SerialPortParameter", "BarityBit", BarityBit.ToString());
            IniAPI.INIWriteValue(PanasonicPath, "SerialPortParameter", "DataBits", DataBits.ToString());
            IniAPI.INIWriteValue(PanasonicPath, "SerialPortParameter", "StopBits", StopBits.ToString());
        }

        /// <summary>
        /// 读取串口参数
        /// </summary>
        public void ReadParameter()
        {
            COM = IniAPI.INIGetStringValue(PanasonicPath, "SerialPortParameter", "COM", "0").ToString();
            BaudRate = Convert.ToInt32(IniAPI.INIGetStringValue(PanasonicPath, "SerialPortParameter", "Baud", "0"));
            BarityBit = Convert.ToInt32(IniAPI.INIGetStringValue(PanasonicPath, "SerialPortParameter", "BarityBit", "0"));
            DataBits = Convert.ToInt32(IniAPI.INIGetStringValue(PanasonicPath, "SerialPortParameter", "DataBits", "0"));
            StopBits = Convert.ToInt32(IniAPI.INIGetStringValue(PanasonicPath, "SerialPortParameter", "StopBits", "0"));
        }

        /// <summary>
        /// 关闭串口
        /// </summary>
        public void ClosePlcServer()
        {
            if (PLC != null)
            {
                PLC.Close();
            }
        }

        /// <summary>
        /// 获取串口设备
        /// </summary>
        /// <param name="comboBox1"></param>
        public bool GetSerialPort()
        {
            try
            {
                //获取本机上所有串口名称
                protname = SerialPort.GetPortNames();
                if (protname.Length > 0)
                {
                    return true;
                }
                return false;
            }
            catch { return false; }
        }

        ~PanasonicMewtocol()
        {
            ClosePlcServer();
        }
    }
}
